<script setup lang="ts">
import TableView from '@/components/TableView.vue'
import { NButton, NDataTable, NPagination, NSpace, useMessage, NP, NModal, NInput } from 'naive-ui'
import { h, ref, reactive, watch, onDeactivated } from 'vue'
import type { DataTableColumns } from 'naive-ui'
import router from '@/router'
import { useRoute } from 'vue-router'
import { sendRequest } from '@/utils/api'
import { useViewerStore } from '../Common/store'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'

const message = useMessage()
const route = useRoute()
const useStore = useViewerStore()

//表格
const rowKey: any = (e: any) => e.id || ''
const columns: DataTableColumns = [
  {
    title: '创建用户',
    key: 'createUserName',
    width: '30rem',
    align: useStore.isCenter
  },
  {
    title: '缩略图',
    key: 'path',
    width: '40rem',
    align: useStore.isCenter,
    render(e) {
      return h('div', null, [
        h('img', {
          style: 'height:50rem;width:50rem;',
          src: e.path
        })
      ])
    }
  },
  {
    title: '标题',
    key: 'title',
    width: '30rem',
    align: useStore.isCenter
  },
  {
    title: '状态',
    key: 'status',
    width: '10rem',
    align: useStore.isCenter,
    render(e: any) {
      return e.status == 1 ? '启用' : '禁用'
    }
  },
  {
    title: '创建时间',
    key: 'createTime',
    width: '30rem',
    align: useStore.isCenter
  },
  {
    title: '操作',
    key: 'action',
    align: useStore.isCenter,
    width: '30rem',
    fixed: 'right',
    render: (e: any) => [
      h(
        NButton,
        { type: 'primary', quaternary: true, onClick: () => handleEdit(e) },
        {
          default: () => '编辑'
        }
      ),
      h(
        NButton,
        {
          type: 'warning',
          quaternary: true,
          color: useStore.color['delete'],
          onClick: () => handleDelete(e)
        },
        {
          default: () => '删除'
        }
      ),
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          style: {
            display: e.status == 0 ? 'inline-block' : 'none'
          },
          onClick: () => handleUse(e)
        },
        {
          default: () => '启用'
        }
      ),
      h(
        NButton,
        {
          type: 'warning',
          quaternary: true,
          color: useStore.color['delete'],
          style: {
            display: e.status == 1 ? 'inline-block' : 'none'
          },
          onClick: () => handleUse(e)
        },
        {
          default: () => '禁用'
        }
      )
    ]
  }
]

const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  onChange: (page: number) => {
    paginationReactive.page = page
    queryTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    queryTableData()
  }
})

//新增
const handleAdd = () => {
  router.push({
    path: '/OA/Affairs/ImgAdd',
    query: {
      id: 0
    }
  })
}

//编辑
const handleEdit = (val: any) => {
  router.push({
    path: '/OA/Affairs/ImgEdit',
    query: {
      id: val.id
    }
  })
}

//启用or禁用
const useContent = ref('')
const useVisiable = ref(false)
const handleUse = (val: any) => {
  useContent.value = val.status ? '您确定要禁用此图片吗?' : '您确定要启用此图片吗?'
  useVisiable.value = true
  modalId.value = val?.id
}

const againUse = async () => {
  tableLoading.value = true
  const [error, res] = await sendRequest({
    module: 'partAffairs',
    api: 'imgStartOrStop',
    override: {
      params: {
        id: modalId.value
      }
    }
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  message.success(res.msg)
  useVisiable.value = false
  tableLoading.value = false
  queryTableData(true)
}

//删除弹窗
const modalVisible = ref(false)
const modalId = ref()
const againDelete = async () => {
  tableLoading.value = true
  const [error, res] = await sendRequest({
    module: 'partAffairs',
    api: 'imgDelete',
    override: {
      data: modalId.value
    }
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  message.success(res.msg)
  modalVisible.value = false
  tableLoading.value = false
  queryTableData(true)
}

const handleDelete = (val: any) => {
  if (val.status == 0) {
    modalId.value = [val?.id]
    modalVisible.value = true
  } else {
    message.warning('请禁用该图片后再删除！')
  }
}

//表格数据
const tableLoading = ref(false)
const tableData: any = ref([])
const title = ref()
const queryTableData = async (resetPage = false) => {
  if (resetPage) paginationReactive.page = 1
  tableLoading.value = true
  const [error, res] = await sendRequest({
    module: 'partAffairs',
    api: 'imgList',
    override: {
      params: {
        page: paginationReactive.page,
        limit: paginationReactive.pageSize,
        title: title.value
      }
    }
  })
  tableLoading.value = false
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  const tmp: any = res.data
  tableData.value = []
  tmp?.list.map((i: any) => {
    tableData.value.push({
      id: i.id,
      createUserName: i.createUserName,
      path: i.sysAnnexFile?.path,
      title: i.title,
      status: i.status,
      createTime: i.createTime
    })
  })
  console.log(tableData.value)
  paginationReactive.itemCount = tmp?.totalCount
}

const keyUpDown = (e: any) => e.key == 'Enter' && (paginationReactive.page = 1,queryTableData(true))
onDeactivated(() => window.removeEventListener('keyup', keyUpDown, false))

watch(
  () => route.path,
  async () => {
    if (route.path == '/OA/Affairs/ImgList') {
      await queryTableData()
      window.addEventListener('keyup', keyUpDown, false)
    }
  },
  { deep: true, immediate: true }
)
</script>

<template>
  <TableView class="table">
    <template #form>
      <NSpace justify="space-between">
        <NSpace justify="center">
          <div style="line-height: 33rem">标题：</div>
          <NInput v-model:value="title" clearable placeholder="请输入标题" />
          <NButton type="primary" style="width: 78px; margin-right: 40rem" ghost @click="queryTableData(true)">
            查询
          </NButton>
        </NSpace>
        <NSpace justify="end">
          <NButton type="primary" style="width: 115px" @click="handleAdd">
            新增
          </NButton>
        </NSpace>
      </NSpace>
    </template>

    <template #table="props">
      <NDataTable v-bind="props" :bordered="false" :row-key="rowKey" :columns="columns" :data="tableData"
        :loading="tableLoading" />
    </template>

    <template #pagination>
      <NPagination :page-sizes="paginationReactive.pageSizes" :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page" :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange" @update:page-size="paginationReactive.onUpdatePageSize"
        show-size-picker show-quick-jumper :suffix="() => '页'">
        <template #prefix>
          <span style="font-size: 14px;"> 共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>

  <NModal :auto-focus="false" v-model:show="modalVisible">
    <VDialogContent @close="modalVisible = false" @submit="againDelete" title="删除提示">
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        您确定要删除吗?
      </div>
    </VDialogContent>
  </NModal>

  <NModal :auto-focus="false" v-model:show="useVisiable">
    <VDialogContent @close="useVisiable = false" @submit="againUse" title="操作提示">
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        {{ useContent }}
      </div>
    </VDialogContent>
  </NModal>
</template>

<style scoped lang="scss">
.table {
  height: 100%;
  padding: 29px 30px 42px;
}
</style>
